package cn.ztydata.teachingsystem.heaven.web.controller;

import cn.ztydata.teachingsystem.heaven.cons.MsgTemplate;
import cn.ztydata.teachingsystem.heaven.entity.KnowledgePoint;
import cn.ztydata.teachingsystem.heaven.service.KpService;
import cn.ztydata.teachingsystem.heaven.web.dto.CourseKpDto;
import cn.ztydata.teachingsystem.heaven.web.dto.KpDto;
import cn.ztydata.teachingsystem.util.StringCodeUtil;
import cn.ztydata.teachingsystem.webservice.result.json.JsonResult;
import cn.ztydata.teachingsystem.webservice.result.json.JsonResultId;
import cn.ztydata.teachingsystem.webservice.result.json.JsonResultList;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.MessageFormat;
import java.util.List;

/**
 * 知识点控制器类
 * Created by chenxin on 2014/12/16.
 */
@Controller
@RequestMapping("/kp")
public class KpController extends BaseController {
    @Autowired
    private KpService kpService;

    /**
     * 搜索知识点
     * @param keyword 搜索关键字
     * @return json
     *
     * @author cx
     * @since 2014-12-09
     */
    @RequestMapping(value = "/search", method = RequestMethod.GET)
    @ResponseBody
    public JsonResultList<CourseKpDto> searchKps(@RequestParam(value = "keyword") String keyword) {
        //转码可能的中文参数
        keyword = StringCodeUtil.urlParamTransCode(keyword, "utf-8");

        //校验参数
        Assert.isTrue(!StringUtils.isBlank(keyword), "搜索关键字不能为空");

        //获取知识点集合
        List<KnowledgePoint> kpList = kpService.searchKps(StringUtils.trim(keyword), 5);
        //集合映射到dto
        List<CourseKpDto> resultList = mapper.mapList(kpList, CourseKpDto.class);

        log.debug("搜索知识点");
        return new JsonResultList<>(resultList);
    }

    /**
     * 新增知识点
     * @param kpDto Dto类
     * @return json结构数据
     *
     * @author chenxin
     * @since 2015/2/6
     */
    @RequestMapping(value = "/addOne", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult addKp(@Valid @RequestBody KpDto kpDto) {
        //映射dto到实体类
        KnowledgePoint kp = mapper.map(kpDto, KnowledgePoint.class);

        //保存新增的知识点
        kpService.addKp(kp);

        log.debug("新增知识点成功");
        return new JsonResultId(kp.getId(), "新增成功");
    }

    /**
     * 删除知识点
     * @param kpId 知识点ID
     * @return json结构数据
     *
     * @author chenxin
     * @since 2015/2/6
     */
    @RequestMapping(value = "/delete/{kpId}", method = RequestMethod.DELETE)
    @ResponseBody
    public JsonResult deleteKp(@PathVariable long kpId) {
        //校验参数
        Assert.isTrue(kpId > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "知识点ID"));

        //删除知识点
        kpService.deleteKp(kpId);

        log.debug("删除知识点成功");
        return new JsonResult(true, "删除成功");
    }
}
